import logging
from datetime import datetime

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods

from db import sel_dict_in_list_lowerkeys
from naryad.models import Spr_sdl
from tarifs.models import Uslugi, Ztarifs


def index(request) -> HttpResponse:
    return render(request, "naryad/load_image.html")


@require_http_methods(["GET"])
def all_usl(request) -> None:
    uslugi_all = Uslugi.objects.filter(isp=1).values(
        "usl", "kusl", "ok_isl_p", "nusl", "opl", "uet", "trf"
    )
    for usl in uslugi_all:
        print(usl)


def load_tarifs():
    try:
        tarif_from_db = sel_dict_in_list_lowerkeys(
            "select * from pl_usl_trf_zp where zn=1 and dk is null"
        )
        for usl in tarif_from_db:
            # print(usl)
            if usl["trf_zp"] == 0:
                print(usl)
            else:
                usluga = Uslugi.objects.filter(kusl=usl["kusl"]).first()
                if usluga is None:
                    print(usl["kusl"], "Нет в справочнике")
                    continue
                sdl = Spr_sdl.objects.get(sdl=usl["sdl"])
                if Ztarifs.objects.filter(usl=usluga, sdl=sdl).exists():
                    continue
                Ztarifs.objects.create(
                    usl=usluga,
                    sdl=sdl,
                    trf_zp=usl["trf_zp"],
                    dn=usl["dn"],
                    type_usl=usl["type_usl"],
                )
    except Exception:
        logging.exception("load_tarifs")
